package com.wuxiaolong.wechat.util;

import com.alibaba.fastjson.JSON;
import com.thoughtworks.xstream.XStream;
import com.wuxiaolong.wechat.common.Constants;
import com.wuxiaolong.wechat.model.BaseMessage;
import com.wuxiaolong.wechat.model.NewsMessage;
import com.wuxiaolong.wechat.model.TextMessage;
import com.wuxiaolong.wechat.service.JuheService;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author Leo
 * @date 2020-02-12
 */
public class BeanXmlUtil {

    /**
     * @title 从InputStream中获取xml数据流，并转换为map对象
     * @param is
     * @return map对象
     */
    public static Map<String, String> xmlToMap(InputStream is) {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();
        try {

            Document doc = reader.read(is);
            Element root = doc.getRootElement();

            @SuppressWarnings("unchecked")
            List<Element> list = root.elements();
            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }




    public static String beanToXmlStr(BaseMessage bean) {

        XStream xStream = new XStream();

        // 使注解生效  每个返回的消息实体类都要写
        xStream.processAnnotations(TextMessage.class);
        xStream.processAnnotations(NewsMessage.class);

        String xmlStr = xStream.toXML(bean);

        return xmlStr;
    }

}
